﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;

namespace Domain
{
    public class Circle : Identified
    {
        private List<Word> _words;
        private Int32 _index = -1;

        public Word Current { get; private set; }

        public String Name { get; private set; }

        public Circle(Guid id, String name, List<Word> words)
            : base(id)
        {
            Name = name;
            _words = words ?? new List<Word>();
            Next();
        }


        public Word Next()
        {
            var newWords = _words.Where(IsNotKnown).ToList();

            if (newWords.IsNullOrEmpty())
            {
                Current = null;
                _index = -1;
            }
            else
            {
                _index = GetNextIndex(_index, newWords.Count());
                Current = newWords[_index];
            }

            return Current;
        }

        private Int32 GetNextIndex(int current, int avalivaleCount)
        {
            var nextIndex = current + 1;
            return nextIndex < avalivaleCount ? nextIndex : 0;
        }

        private static bool IsNotKnown(Word w)
        {
            return !IsKnown(w);
        }

        private static bool IsKnown(Word w)
        {
            return (DateTime.UtcNow - w.LastKnownDate).TotalDays < 3;
        }

        public Boolean IsEmpty()
        {
            return _words.IsNullOrEmpty();
        }

        public Boolean IsKnown()
        {
            return _words.All(IsKnown);
        }

        public List<Word> ToList()
        {
            return _words;
        }

        public void Add(Word w)
        {
            _words.Add(w);
            if (Current == null)
            {
                IsNotKnown(w);
                Current = w;
            }
        }

    }
}
